<template>
  <div style="margin: -20px 0 0 -20px; height: 90%">
    <el-container>
      <!-- 历史对话记录 -->
      <el-aside width="collapse" style="background-color: white;">
        <el-menu :collapse="isCollapse" class="custom-menu" mode="vertical" v-if="sessionList.length <= 0">
          <el-empty description="历史对话为空"></el-empty>
        </el-menu>
        <el-menu
            v-if="sessionList.length > 0"
            :collapse="isCollapse"
            class="custom-menu"
            mode="vertical"
            v-for="(item, index) in sessionList" :key="index">
          <el-menu-item v-if="index===0 && isNew">
            <template>
              <span slot="title" style="color: black;">历史对话</span>
            </template>
          </el-menu-item>
          <el-menu-item v-if="index===0 && !isNew" @click="newDialogue">
            <template>
              <span slot="title" style="color: black;">
                <i class="el-icon-plus"></i>新建对话
              </span>
            </template>
          </el-menu-item>
          <el-menu-item @click="getOneSession(item._id)">
            <template>
              <span slot="title" style="color: black;">{{ item.name }}</span>
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-button class="header1" title="isCollapse ? '点击展开' : '点击收起'" @click="isC">
          <i :class="!isCollapse ? 'el-icon-arrow-left' : 'el-icon-arrow-right'"></i>
        </el-button>
        <!-- 对话详细信息 or 对话主页 -->
        <el-main style="height: 720px; padding-bottom: 50px" id="dh">
          <div v-for="(item, index) in sessionData" :key="index" v-if="!isNew">
            <!-- user问 -->
            <div style="width: 100%; height: 100%; float: right; margin-bottom: 20px; position: relative;">
              <div class="question">
                <el-card class="question-card">
                  {{ item.question }}
                </el-card>
                <el-avatar :size="60" class="user-img" :src="require('@/assets/images/img.png')"></el-avatar>
              </div>
            </div>
            <br>
            <!-- ai答 -->
            <div class="answer">
              <el-avatar :size="60" class="ai-img" :src="require('@/assets/images/aijqr.png')"></el-avatar>
              <el-card class="answer-card" >
                <span v-html="answerMarkdownList[index] "></span>
              </el-card>
            </div>
            <br>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <!-- 新对话输入框 -->
    <div class="dialogue" @keydown.enter="handleEnter">
      <el-card class="dialogue-card">
        <el-input class="input-text" v-model="text" type="textarea" :autosize="{ minRows: 2, maxRows: 3}" resize="none"
                  :rows="2" placeholder="请输入内容"></el-input>
        <el-button class="button1" @click="dialogue"><i class="el-icon-s-promotion" style="float: right;"></i>
        </el-button>
      </el-card>
    </div>
  </div>
</template>

<script>
import aiApi from "@/assets/api/aiApi";
export default {
  data() {
    return {
      isNew: true,
      isCollapse: false, // 默认为展开
      sessionList: [],
      sessionData: [],
      // 用户数据
      user: {
        name: ''
      },
      text: null,
      _id: null,
      // 用于存储解析后的HTML
      answerMarkdownList: [],
    }
  },
  created() {
    this.getCookie()
  },
  mounted() {
    this.getSessionList()
  },
  methods: {
    newDialogue(){
      this.isNew = true
    },
    handleEnter(event) {
      event.preventDefault();
      event.stopPropagation();
      this.dialogue(); // 模拟按钮点击
    },
    // 对话
    dialogue() {
      if (this.text !== null && this.text !== " ") {
        aiApi.ERNIESpeed128K({
          _id: this._id,
          userName: this.user.name,
          text: this.text
        }).then(res => {
          if(this._id == null){
            this.getSessionList()
            setTimeout(()=>{
              this.getOneSession(this.sessionList[0]._id)
            }, 888)
          }else {
            this.getOneSession(this._id)
          }
        })
        this.text = null
      } else {
        this.$message.error("输入内容不能为空")
      }
    },
    // 动态控制展开与收起和切换对应图标
    isC() {
      this.isCollapse = !this.isCollapse;
    },
    // 获取历史话题
    getSessionList() {
      aiApi.getSessionList({
        userName: this.user.name
      }).then(res => {
        this.sessionList = res.data;
      })
    },
    // 获取一个会话信息
    getOneSession(_id) {
      this.isNew = false
      this._id = _id;
      aiApi.getOneSession({
        userName: this.user.name,
        id: this._id
      }).then(res => {
        this.sessionData = res.data;
        // 由于键名没有直接的顺序，我们需要先找到所有的问题和答案，然后配对
        const questions = [];
        const answers = [];
        // 遍历对象，分离问题和答案
        for (const key in res.data) {
          if (key.startsWith('questions')) {
            questions.push(res.data[key]);
          } else if (key.startsWith('answers')) {
            answers.push(res.data[key]);
          }
        }
        // 配对问题和答案（假设它们按顺序给出）
        const qaPairs = [];
        for (let i = 0; i < questions.length; i++) {
          qaPairs.push({
            question: questions[i],
            answer: answers[i]
          });
          const marked = require('marked');
          this.answerMarkdownList[i] = marked.parse(answers[i]);
        }
        this.sessionData = qaPairs;
        // 滑到底部
        this.$nextTick(() => {
          let container = document.getElementById("dh");
          container.scrollTop = container.scrollHeight; // 滚动到底部
        })
      })
    },
    // 读取cookie中的账户和密码
    getCookie: function () {
      let that = this;
      if (document.cookie.length > 0) {
        let arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (let i = 0; i < arr.length; i++) {
          let arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] === "account") {
            that.user.name = arr2[1]; //保存到保存数据的地方
          }
        }
      }
    }
  }
}
</script>

<style>
@import "../assets/css/ai.css";
</style>